package com.ldy.job.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.ldy.job.ReportUtilsApplication;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ldy.job.utils.ExcelUtils.RESSTR_XIANSHANGHUALV;
import static com.ldy.job.utils.ExcelUtils.RESSTR_YEWUYUNXINGFENXI;
import static com.ldy.job.utils.PPTUtils.changPPT;

@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private static final String[] INDEX_STR = new String[25];
    private static final String[] INDEX_STR2 = new String[3];
    private Map<String, String> tempData = new LinkedHashMap<>();
    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    static {
        INDEX_STR[0] = "5_18";
        INDEX_STR[1] = "5_22";
        INDEX_STR[2] = "5_26";
        INDEX_STR[3] = "5_30";
        INDEX_STR[4] = "5_34";
        INDEX_STR[5] = "5_38";
        INDEX_STR[6] = "5_42";
        INDEX_STR[7] = "5_46";

        INDEX_STR[8] = "5_23";
        INDEX_STR[9] = "5_25";
        INDEX_STR[10] = "5_31";
        INDEX_STR[11] = "5_33";
        INDEX_STR[12] = "5_39";
        INDEX_STR[13] = "5_41";
        INDEX_STR[14] = "5_47";
        INDEX_STR[15] = "5_49";

        INDEX_STR[16] = "5_87";

        INDEX_STR[17] = "5_50";
        INDEX_STR[18] = "5_18";
        INDEX_STR[19] = "5_74";
        INDEX_STR[20] = "5_82";
        INDEX_STR[21] = "5_55";
        INDEX_STR[22] = "5_23";
        INDEX_STR[23] = "5_79";
        INDEX_STR[24] = "5_87";

        INDEX_STR2[0] = "5_18";
        INDEX_STR2[1] = "5_23";
        INDEX_STR2[2] = "5_25";
    }

    StringBuffer resStr = new StringBuffer("\r\n 本月：\t");

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
//        log.info("解析行数:{}", context.readRowHolder().getRowIndex());
//        log.info("解析到一条数据:{}", data);
        cachedDataList.add(data);
        for (int i = 0; i < INDEX_STR.length; i++) {
            String string = INDEX_STR[i];
            String[] index = string.split("_");
            if (context.readRowHolder().getRowIndex().equals(Integer.parseInt(index[0]))) {
                String s = data.get(Integer.parseInt(index[1]));
                if (s != null && !s.contains("%")) {
                    s = amountTool(s);
                }
                if (i == 7) {
                    resStr.append(s).append("\r\n 本年：\t");
                } else if (i == 15) {
                    resStr.append(s).append("\r\n 本年线上化率：\t");
                } else if (i > 16) {
                    RESSTR_XIANSHANGHUALV = RESSTR_XIANSHANGHUALV.replaceFirst("#X#", s);
                    log.info(RESSTR_XIANSHANGHUALV);
                } else {
                    resStr.append(s).append("\t\t");
                }

                if (i < 17) {
                    tempData.put(string, s);
                }
            }
        }
        for (int i = 0; i < INDEX_STR2.length; i++) {
            String string = INDEX_STR2[i];
            String[] index = string.split("_");
            if (context.readRowHolder().getRowIndex().equals(Integer.parseInt(index[0]))) {
                String s = data.get(Integer.parseInt(index[1]));
                if (s != null && !s.contains("%")) {
                    s = amountTool(s);
                }
                RESSTR_YEWUYUNXINGFENXI = RESSTR_YEWUYUNXINGFENXI.replaceFirst("#N#", s);
                log.info(RESSTR_YEWUYUNXINGFENXI);
            }
        }
        if (cachedDataList.size() >= BATCH_COUNT) {
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    public static String amountTool(String amount) {
        if (amount.contains(",") || !isNumeric(amount)) {
            return amount;
        }
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setCurrencySymbol("");
        DecimalFormat currencyFormat = new DecimalFormat("#,##0");
        currencyFormat.setDecimalFormatSymbols(symbols);
        return currencyFormat.format(Integer.parseInt(amount));
    }

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            int chr = str.charAt(i);
            if (chr < 48 || chr > 57) return false;
        }
        return true;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info(resStr.toString());
        tempData.put("y", getLastYear());
        tempData.put("m", getLastMonth());
        changPPT(ReportUtilsApplication.DOC_PATH + "\\模板\\“单一窗口”及信保易线上签单情况月报-模版.pptx", ReportUtilsApplication.DOC_PATH + "\\生成\\“单一窗口”及信保易线上签单情况月报(" + getLastMonth() + "月).pptx", tempData);
    }

    /**
     * 获取当前月的上一个月
     *
     * @return
     */
    public static String getLastMonth() {
        SimpleDateFormat format = new SimpleDateFormat("MM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.add(Calendar.MONTH, -1);
        date = calendar.getTime();
        String res = format.format(date);
        if (res.startsWith("0")) {
            res = res.replace("0", "");
        }
        return res;
    }

    /**
     * 获取当前月的上一个月所在年
     *
     * @return
     */
    public static String getLastYear() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.add(Calendar.MONTH, -1);
        date = calendar.getTime();
        String res = format.format(date);
        if (res.startsWith("0")) {
            res = res.replace("0", "");
        }
        return res;
    }

    /**
     * 获取当前月
     *
     * @return
     */
    public static String getMonth() {
        SimpleDateFormat format = new SimpleDateFormat("MM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        date = calendar.getTime();
        String res = format.format(date);
        if (res.startsWith("0")) {
            res = res.replace("0", "");
        }
        return res;
    }

}
